package sysDao

import (
	"context"
	"fmt"
	"gitee.com/jokces/kit/errc"
	sysModel "gitee.com/jokces/kit/global/admin/model"
	"xorm.io/xorm"
)

// DepList 部门
func (d *Dao) DepList(ctx context.Context, req *sysModel.SysDep) ([]*sysModel.SysDep, error) {
	arr := make([]*sysModel.SysDep, 0)
	sess := d.dao.Context(ctx)
	sess.And("is_del = 0")
	if req.Id > 0 {
		sess.And("id = ?", req.Id)
	}
	if req.ParentId > 0 {
		sess.And("parent_id = ?", req.ParentId)
	}
	if req.Status > 0 {
		sess.And("`status` = ?", req.Status)
	}
	if req.DepName != "" {
		sess.And("dep_name = ?", req.DepName)
	}
	if req.DepCode != "" {
		sess.And("dep_code = ?", req.DepCode)
	}
	if req.LikeDepCode != "" {
		sess.And("dep_code like ?", req.LikeDepCode+"%")
	}
	if req.LikeDepName != "" {
		sess.And("dep_name like ?", req.LikeDepName+"%")
	}
	err := sess.Asc("id").Find(&arr)
	return arr, errc.WithStack(err)
}
func (d *Dao) DepGetOne(ctx context.Context, req *sysModel.SysDep) (bool, *sysModel.SysDep, error) {
	rs := &sysModel.SysDep{}
	deps, err := d.DepList(ctx, req)
	if err != nil {
		return false, rs, err
	}
	if len(deps) > 0 {
		return true, deps[0], nil
	}
	return false, rs, nil
}
func (d *Dao) DepAdd(in, parent *sysModel.SysDep) error {
	err := d.dao.Transaction(func(sess *xorm.Session) error {
		if row, err := sess.InsertOne(in); err != nil {
			return err
		} else if row != 1 {
			return errc.ErrInternalErr.MultiMsg("add dep error")
		}

		in.DepCode = fmt.Sprintf("%v,%v", parent.DepCode, in.Id)

		if row, err := sess.ID(in.Id).Cols("dep_code").Update(in); err != nil {
			return err
		} else if row != 1 {
			return errc.ErrInternalErr.MultiMsg("add dep error")
		}
		return nil
	})
	if err != nil {
		return errc.WithStack(err)
	}
	return nil
}
